/**
 * 课程学习页面组件
 * 处理各种练习题目，包括翻译、选择、听力等
 * 包含心跳系统、进度跟踪、结果反馈和动画效果
 */
import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Alert,
  Animated,
  Dimensions,
  BackHandler,
  ScrollView
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import * as Progress from 'react-native-progress';

import { lessonsData } from '../data/lessons';
import { completeLesson } from '../utils/storage';
import {
  TranslationExercise,
  MultipleChoiceExercise,
  ListeningExercise,
  GrammarFillExercise,
  ReadingComprehensionExercise,
  ExerciseResult
} from '../components/ExerciseComponents';
// 导入动画组件
import { LevelUpAnimation, PulseAnimation, FloatingAnimation } from '../components/AnimatedComponents';
import {
  AppButton,
  EmptyState,
  LoadingIndicator
} from '../components/CommonUI';
import { LessonHeader } from '../components/Headers';

const { width, height } = Dimensions.get('window');

/**
 * 课程学习页面组件
 * @param {Object} route - 路由参数，包含 lessonId
 * @param {Object} navigation - 导航对象
 */
export default function LessonScreen({ route, navigation }) {
  const { lessonId } = route.params;
  const lesson = lessonsData.find(l => l.id === lessonId);
  
  // 组件状态定义
  const [currentExerciseIndex, setCurrentExerciseIndex] = useState(0); // 当前题目索引
  const [selectedAnswer, setSelectedAnswer] = useState(null);           // 用户选择的答案
  const [showResult, setShowResult] = useState(false);                 // 是否显示结果
  const [isCorrect, setIsCorrect] = useState(false);                   // 答案是否正确
  const [score, setScore] = useState(0);                               // 当前得分
  const [hearts, setHearts] = useState(3);                             // 剩余心跳数
  const [lessonCompleted, setLessonCompleted] = useState(false);       // 课程是否完成
  const [fadeAnim] = useState(new Animated.Value(1));                  // 动画值
  const [startTime] = useState(new Date());                            // 开始时间
  // 新增动画状态
  const [showLevelUpAnimation, setShowLevelUpAnimation] = useState(false); // 是否显示升级动画
  const [newLevel, setNewLevel] = useState(1);                             // 新级别

  // 计算课程进度
  const currentExercise = lesson?.exercises[currentExerciseIndex];
  const totalExercises = lesson?.exercises.length || 0;
  const progress = totalExercises > 0 ? (currentExerciseIndex + 1) / totalExercises : 0;

  // 处理返回按钮点击
  useEffect(() => {
    const backHandler = BackHandler.addEventListener('hardwareBackPress', handleBackPress);
    return () => backHandler.remove();
  }, []);

  /**
   * 处理返回按钮点击
   * 显示确认对话框，防止意外退出
   */
  const handleBackPress = () => {
    Alert.alert(
      '退出课程',
      '你确定要退出吗？当前的学习进度将会丢失。',
      [
        { text: '取消', style: 'cancel' },
        { text: '退出', style: 'destructive', onPress: () => navigation.goBack() }
      ]
    );
    return true;
  };

  /**
   * 处理用户选择答案
   * @param {number} answerIndex - 答案索引
   */
  const handleAnswer = (answerIndex) => {
    if (showResult) return; // 已显示结果时不能再选择
    setSelectedAnswer(answerIndex);
  };

  /**
   * 检查答案正确性并显示结果
   */
  const checkAnswer = () => {
    if (selectedAnswer === null) {
      Alert.alert('请选择答案', '请选择一个选项后继续。');
      return;
    }

    const correct = selectedAnswer === currentExercise.correct;
    setIsCorrect(correct);
    setShowResult(true);

    if (correct) {
      setScore(score + 1);
      // 正确答案的成功动画 - 优化布局，避免干扰界面
      Animated.sequence([
        Animated.timing(fadeAnim, { 
          toValue: 0.95, 
          duration: 150, 
          useNativeDriver: true 
        }),
        Animated.timing(fadeAnim, { 
          toValue: 1, 
          duration: 150, 
          useNativeDriver: true 
        })
      ]).start();
    } else {
      // 错误答案，扣除心跳
      const newHearts = Math.max(0, hearts - 1);
      setHearts(newHearts);
      
      // 检查是否心跳耗尽
      if (newHearts <= 0) {
        setTimeout(() => {
          Alert.alert(
            '游戏结束',
            '你的心跳已经用完了！不要灰心，再试一次吧！',
            [
              { text: '重新开始', onPress: resetLesson },
              { text: '退出', onPress: () => navigation.goBack() }
            ]
          );
        }, 1500);
        return;
      }
    }
  };

  /**
   * 重置课程到初始状态
   */
  const resetLesson = () => {
    setCurrentExerciseIndex(0);
    setSelectedAnswer(null);
    setShowResult(false);
    setIsCorrect(false);
    setScore(0);
    setHearts(3);
    setLessonCompleted(false);
    // 重置动画
    fadeAnim.setValue(1);
  };

  /**
   * 处理继续按钮点击
   * 进入下一题或完成课程
   */
  const handleContinue = async () => {
    setShowResult(false);
    setSelectedAnswer(null);

    if (currentExerciseIndex < totalExercises - 1) {
      // 进入下一题
      setCurrentExerciseIndex(currentExerciseIndex + 1);
    } else {
      // 课程完成
      setLessonCompleted(true);
      
      try {
        // 计算学习时间
        const endTime = new Date();
        const studyTime = Math.round((endTime - startTime) / 1000); // 秒
        const accuracy = Math.round((score / totalExercises) * 100); // 准确率
        
        // 保存课程完成情况
        const result = await completeLesson(lessonId, lesson.xp, score);
        
        // 检查是否升级，如果升级先显示升级动画
        if (result.leveledUp) {
          setNewLevel(result.level);
          setShowLevelUpAnimation(true);
          // 延迟显示完成对话框，等待动画完成
          setTimeout(() => {
            showCompletionDialog(result, accuracy, studyTime, true);
          }, 3000); // 3秒后显示对话框
        } else {
          // 没有升级，直接显示完成对话框
          showCompletionDialog(result, accuracy, studyTime, false);
        }
        
        // 显示完成庆祝页面
        const congratsMessage = `
太棒了！你获得了 ${lesson.xp} 经验值！

📊 本次成绩：
• 正确率：${accuracy}% (${score}/${totalExercises})
• 学习时间：${studyTime}秒
• 当前等级：${result.level}
• 总经验值：${result.totalXP}
        `;
        
        let alertTitle = '课程完成！🎉';
        if (result.leveledUp) {
          alertTitle = `升级了！现在是 ${result.level} 级！🎆`;
        }
      } catch (error) {
        console.error('完成课程失败:', error);
        Alert.alert('错误', '保存进度失败，请重试。');
      }
    }
  };

  /**
   * 显示课程完成对话框
   * @param {Object} result - 课程完成结果
   * @param {number} accuracy - 准确率
   * @param {number} studyTime - 学习时间
   * @param {boolean} hasLeveledUp - 是否升级
   */
  const showCompletionDialog = (result, accuracy, studyTime, hasLeveledUp) => {
    // 显示完成庆祝页面
    const congratsMessage = `
太棒了！你获得了 ${lesson.xp} 经验值！

📊 本次成绩：
• 正确率：${accuracy}% (${score}/${totalExercises})
• 学习时间：${studyTime}秒
• 当前等级：${result.level}
• 总经验值：${result.totalXP}
    `;
    
    let alertTitle = '课程完成！🎉';
    if (hasLeveledUp) {
      alertTitle = `升级了！现在是 ${result.level} 级！🎆`;
    }
    
    Alert.alert(
      alertTitle,
      congratsMessage,
      [{ text: '继续学习', onPress: () => navigation.goBack() }]
    );
  };

  /**
   * 升级动画完成回调
   */
  const handleLevelUpAnimationComplete = () => {
    setShowLevelUpAnimation(false);
  };

  /**
   * 渲染当前练习题目
   * 根据题目类型显示不同的组件
   */
  const renderExercise = () => {
    if (!currentExercise) return null;

    const exerciseProps = {
      exercise: currentExercise,
      onAnswer: handleAnswer,
      selectedAnswer: selectedAnswer
    };

    switch (currentExercise.type) {
      case 'translation':
        return <TranslationExercise {...exerciseProps} />;
      case 'multiple_choice':
        return <MultipleChoiceExercise {...exerciseProps} />;
      case 'listening':
        return <ListeningExercise {...exerciseProps} />;
      case 'grammar_fill': // 语法填空题型
        return <GrammarFillExercise {...exerciseProps} />;
      case 'reading_comprehension': // 阅读理解题型
        return <ReadingComprehensionExercise {...exerciseProps} />;
      default:
        return (
          <View style={styles.errorContainer}>
            <Ionicons name="warning-outline" size={48} color="#FF6B6B" />
            <Text style={styles.errorText}>未知的题目类型：{currentExercise.type}</Text>
          </View>
        );
    }
  };

  /**
   * 渲染答题结果页面
   */
  const renderResult = () => {
    const correctAnswer = currentExercise.options[currentExercise.correct];
    const explanation = currentExercise.explanation || null;

    return (
      <ExerciseResult
        isCorrect={isCorrect}
        correctAnswer={correctAnswer}
        explanation={explanation}
        onContinue={handleContinue}
      />
    );
  };

  // 课程不存在的错误处理
  if (!lesson) {
    return (
      <SafeAreaView style={styles.errorContainer}>
        <EmptyState 
          icon="document-outline"
          title="找不到该课程"
          description={`课程ID: ${lessonId}`}
          actionButton={
            <AppButton 
              title="返回"
              onPress={() => navigation.goBack()}
              variant="secondary"
            />
          }
        />
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container} edges={['top', 'bottom']}>
      {/* 使用新的LessonHeader组件 */}
      <LessonHeader
        onClose={handleBackPress}
        progress={progress}
        hearts={hearts}
        maxHearts={3}
      />

      {/* 练习内容区域 */}
      <ScrollView 
        style={styles.content}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
        bounces={false}
      >
        {/* 题目进度显示 */}
        <View style={styles.questionProgressContainer}>
          <Text style={styles.questionProgressText}>
            题目 {currentExerciseIndex + 1} / {totalExercises}
          </Text>
        </View>
        
        <Animated.View style={[styles.exerciseWrapper, { opacity: fadeAnim }]}>
          {showResult ? renderResult() : renderExercise()}
        </Animated.View>
      </ScrollView>

      {/* 底部按钮区域 */}
      {!showResult && (
        <View style={styles.bottomContainer}>
          <AppButton
            title="检查答案"
            onPress={checkAnswer}
            disabled={selectedAnswer === null}
            variant={selectedAnswer === null ? 'disabled' : 'primary'}
            style={styles.checkButton}
          />
        </View>
      )}

      {/* 升级动画 - 修复遮罩显示问题 */}
      {showLevelUpAnimation && (
        <View style={styles.levelUpOverlay}>
          <View style={styles.levelUpBackground} />
          <LevelUpAnimation 
            isVisible={showLevelUpAnimation}
            newLevel={newLevel}
            onAnimationComplete={handleLevelUpAnimationComplete}
          />
        </View>
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  // 多邻国风格的Header设计
  header: {
    backgroundColor: '#58CC02',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingVertical: 15,
    elevation: 5,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
  },
  closeButton: {
    padding: 5,
    width: 40,
  },
  // Header中间的进度条区域
  headerProgressContainer: {
    flex: 1,
    alignItems: 'center',
    paddingHorizontal: 20,
  },
  heartsContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    width: 80,
    justifyContent: 'flex-end',
  },
  heart: {
    marginLeft: 5,
  },
  // 题目进度显示区域
  questionProgressContainer: {
    alignItems: 'center',
    paddingVertical: 15,
    backgroundColor: '#fff',
    marginBottom: 10,
    borderRadius: 10,
    marginHorizontal: 5,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
  },
  questionProgressText: {
    fontSize: 14,
    fontWeight: '600',
    color: '#666',
  },
  content: {
    flex: 1,
    paddingTop: 10,
  },
  scrollContent: {
    flexGrow: 1,
    paddingHorizontal: 20,
    paddingBottom: 20,
  },
  exerciseWrapper: {
    flex: 1,
    minHeight: height * 0.4,
  },
  bottomContainer: {
    backgroundColor: '#fff',
    paddingHorizontal: 20,
    paddingVertical: 15,
    paddingBottom: 25,
    elevation: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: -2 },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    borderTopLeftRadius: 15,
    borderTopRightRadius: 15,
  },
  // 修复后的升级动画遮罩层
  levelUpOverlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 10000,
    justifyContent: 'center',
    alignItems: 'center',
  },
  // 升级动画背景
  levelUpBackground: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0,0,0,0.8)',
  },
  checkButton: {
    backgroundColor: '#58CC02',
    borderRadius: 15, // 更圆润的圆角，参考多邻国
    paddingVertical: 18, // 增加按钮高度
    alignItems: 'center',
    elevation: 3,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
  },
  disabledButton: {
    backgroundColor: '#E5E5E5', // 更明显的禁用状态
  },
  checkButtonText: {
    color: '#fff',
    fontSize: 16, // 稍小一些的字体
    fontWeight: '700', // 更加加粗
    letterSpacing: 0.5,
  },
  disabledButtonText: {
    color: '#999',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  errorText: {
    fontSize: 18,
    color: '#666',
    textAlign: 'center',
    marginBottom: 10,
  },
  errorSubtext: {
    fontSize: 14,
    color: '#999',
    textAlign: 'center',
    marginBottom: 20,
  },
  backButton: {
    backgroundColor: '#58CC02',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 20,
  },
  backButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  // 移除调试信息相关样式
});